package cn.iocoder.yudao.framework.prometheus.ws;

import cn.hutool.core.util.StrUtil;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
public class WebSocketMessageMetrics {
    @Resource
    private MeterRegistry registry;

    public WebSocketMessageMetrics() {
    }

    // 增加收到的消息总数
    public void recordReceivedMessage(String path) {
        if (StrUtil.isEmpty(path)) {
            path = "unknown";
        }

        final Counter counter = Counter.builder("websocket.messages.receive")
                .description("WebSocket 收到的消息总数")
                .tag("protocol", "ws")  // 可选：添加标签区分协议类型
                .tag("provider", "netty")
                .tag("uri", path)
                .register(registry);
        counter.increment();

        final long count = (long) counter.count();
        if (count % 50 == 0) {
            log.warn("收到的消息总数: {}", count);
        }
    }

    // 增加正在处理的消息总数
    public void recordProcessingMessage(String path) {
        if (StrUtil.isEmpty(path)) {
            path = "unknown";
        }

        final Counter counter = Counter.builder("websocket.messages.processing")
                .description("WebSocket 正在处理的消息总数")
                .tag("protocol", "ws")  // 可选：添加标签区分协议类型
                .tag("provider", "netty")
                .tag("uri", path)
                .register(registry);
        counter.increment();

        final long count = (long) counter.count();
        if (count % 50 == 0) {
            log.warn("正在处理的消息总数: {}", count);
        }
    }

    // 增加异常消息总数
    public void recordNettyExceptionMessage(String path) {
        if (StrUtil.isEmpty(path)) {
            path = "unknown";
        }

        final Counter counter = Counter.builder("websocket.messages.exception.netty")
                .description("WebSocket Netty异常消息总数")
                .tag("protocol", "ws")  // 可选：添加标签区分协议类型
                .tag("provider", "netty")
                .tag("uri", path)
                .register(registry);
        counter.increment();

        final long count = (long) counter.count();
        if (count % 50 == 0) {
            log.warn("Netty异常消息总数: {}", count);
        }
    }

}
